package br.ufpb.di.ppgi.apresentacao.controllers;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Hibernate;
import br.com.caelum.vraptor.view.Results;
import br.com.simtecnologia.access.controll.annotation.ControlledResource;
import br.com.simtecnologia.access.controll.role.Roles;
import br.ufpb.di.ppgi.negocio.ServiceLocator;
import br.ufpb.di.ppgi.negocio.iservicos.IProfessorExternoService;
import br.ufpb.di.ppgi.negocio.modelo.professorExterno.ProfessorExterno;
import br.ufpb.di.ppgi.persistencia.transaction.TransactionScoped;

@Path("/admin/professores-convidados/")
@ControlledResource
@Roles({"SECRETARIO"})
public class ProfessorExternoRestrictController extends AbstractController {
	
	private final IProfessorExternoService servico;
	private final ServiceLocator serviceLocator;
	

	public ProfessorExternoRestrictController(Result result, Validator validator,
			ServiceLocator services) {
		super(result, validator, services);

		this.servico = services.forProfessorExterno();
		this.serviceLocator = services;
	}
	
	@Get
	@Path("")
	public void index() {
		result.include("professorExternos", servico.listar());
	}
	
	@Get
	@Path({"editarProfessorExterno-{id}","inserir"})
	public void formProfessorExterno(Long id) {
		result.include("professores", serviceLocator.forUsuario().listarProfessores());		
		result.include("professorExterno", id == null ? null : servico.buscar(id));
		
	}
	
	@Get
	@Path("inserirDialog-{propostaId}")
	public void form(Long id, Long propostaId) {
		result.include("profExterno", id == null ? null : serviceLocator.forProfessorExterno().buscar(id));
		result.include("propostaId", propostaId);
	}
	
	@Get
	@Path("historico-{id}")
	public void historico(Long id) {
		result.include("usuario", servico.buscar(id));
	}
	
	@Get
	@Path("{id}")
	@Roles({"COORDENADOR"})
	public void detalhes(Long id) {
		ProfessorExterno externo = services.forProfessorExterno().buscar(id);
		
		result.include("externo", externo);
	}
	
	@Post
	@Path("salvar")
	@TransactionScoped
	public void persistirProfessorExterno(ProfessorExterno profExterno, Long propostaId) {
		validator.addAll(Hibernate.validate(profExterno));
		validator.onErrorUse(Results.logic()).redirectTo(getClass()).form(profExterno.getId(), propostaId);
		
		if (profExterno.getId() != null)
			serviceLocator.forProfessorExterno().atualizar(profExterno);			
		
		else
			serviceLocator.forProfessorExterno().adicionar(profExterno);
		
		result.redirectTo(DefesasRestrictController.class).solicitar(propostaId);
	}

	
	@Get
	@Path("removerProfessorExterno-{id}")
	@TransactionScoped
	public void removerProfessorExterno(Long id) {
		if (id != null)
			servico.apagar(id);
		
		result.redirectTo(this).index();
	}
	
}